package cn.lijiajia3515.cairo.security.context;

import cn.lijiajia3515.cairo.domain.CairoAccount;
import cn.lijiajia3515.cairo.security.authentication.CairoAuthenticationToken;
import cn.lijiajia3515.cairo.security.oauth2.resource.server.authentication.CairoJwtAuthenticationToken;
import cn.lijiajia3515.cairo.security.oauth2.jwt.CairoJwtPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;

import java.security.Principal;
import java.util.Collections;
import java.util.Optional;

public class CairoSecurityContextHolder {

	public final static CairoAccount DEFAULT_USER = CairoAccount.builder()
		.id("default")
		.login("default")
		.nickname("匿名用户")
		.email("default@haofangsoft.com")
		.phoneNumber("11111111111")
		.departments(Collections.emptyList())
		.roles(Collections.emptyList())
		.build();

	public static CairoAccount authenticationAccount() {
		return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
			.flatMap(authentication -> {
				if (authentication instanceof CairoJwtAuthenticationToken) {
					return Optional.ofNullable(((CairoJwtAuthenticationToken) authentication).getPrincipal())
						.map(CairoJwtPrincipal::getAccount);
				} else if (authentication instanceof CairoAuthenticationToken) {
					return Optional.of(((CairoAuthenticationToken) authentication).getPrincipal());
				}
				return Optional.empty();
			})
			.orElse(DEFAULT_USER);
	}

	public static String authenticationAccountId() {
		return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
			.map(Principal::getName)
			.orElse(DEFAULT_USER.getId());
	}
}
